package com.novatec.mvc.controlador;

import java.text.ParseException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.novatec.mvc.modelo.CajasItem;
import com.novatec.mvc.servicio.CajasService;

@Controller
public class Cajas {
	private final Logger logger = Logger.getLogger(Cajas.class);
	
	@Autowired
	private CajasService cajasService;
	
	@RequestMapping(value = "/contenedor", method = RequestMethod.GET)
	public ModelAndView regCajas() {
		
		logger.debug("inicio: contenedores");
		return new ModelAndView("formTipoCajas", "command", new CajasItem());
	}
	
	@RequestMapping(value = "/contenedor", method = RequestMethod.POST)
	public ModelAndView crearCajas(@ModelAttribute("formTipoCajas")
            CajasItem cajasItem, BindingResult result) throws DataAccessException, ParseException {

		String flagValidaNombre=null;
		ModelAndView mav=new ModelAndView("formTipoCajas", "command", new CajasItem());
		
	    try{	    	
			List lista=cajasService.validarNombreModelo(cajasItem);
			if(lista.size()>0)
				flagValidaNombre="repetido";
			else{
				cajasService.guardarCajas(cajasItem);
			}		
			mav.addObject("flagValidaNombre", flagValidaNombre);
	    }
	    catch(Exception e){
	    	e.printStackTrace();
	    }
		
		return mav;
	}
	
	@RequestMapping("/tipoCajas")
	public ModelAndView tipoCajas(HttpServletRequest req,
			HttpServletResponse res) throws ParseException {
		
		ModelAndView mavPedido = new ModelAndView("formTipoCajas");
		
		
		
		return mavPedido;
	}
}
